// 和用户相关的状态管理
// models是模块管理子文件夹
import { createSlice } from "@reduxjs/toolkit";
import { getToken, request } from "../../utils";
import { loginAPI, getUserInfoAPI } from "../../apis/user";
import { setToken as _setToken, getToken as _getToken } from "../../utils";
import { removeToken } from "../../utils";
const userStore = createSlice({
  // 当前的模块名
  name: "user",
  //   数据状态
  initialState: {
    token: _getToken() || "",
    userInfo: {},
  },
  // 同步修改方法
  reducers: {
    // 第一个参数是状态，第二个参数是修改的描述对象
    setToken(state, action) {
      state.token = action.payload;
      // localStorage.setItem("token", action.payload);
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    // 清除用户信息
    clearUser(state) {
      (state.userInfo = {}), (state.token = "");
      removeToken();
    },
  },
});
//结构出actionCreater
const { setToken, setUserInfo, clearUser } = userStore.actions;
// 获取reducer函数,修改状态的函数方法
const userReducer = userStore.reducer;
// 异步方法，完成登录获取token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    // // 1.发送异步请求
    // const res = await request.post("/authorizations", loginForm);
    // //2.提价同步action进行token存入
    // // dispatch(setToken(res.data.token));
    // const res = await loginAPI(loginForm);
    console.log(loginForm, "aaa");

    dispatch(setToken(res.data.token));
  };
};
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoAPI();
    dispatch(setUserInfo(res.data));
  };
};
export { fetchLogin, fetchUserInfo, clearUser };
export default userReducer;
